package com.xiaoy.core.basic.organization.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.xiaoy.core.basic.organization.entity.Organization;
import com.xiaoy.core.basic.organization.entity.Party;
import com.xiaoy.core.basic.organization.entity.PartyType;
import com.xiaoy.core.basic.organization.service.OrganizationService;
import com.xiaoy.core.basic.organization.service.PartyTypeSerivce;
import com.xiaoy.core.basic.security.entity.PartyRole;
import com.xiaoy.exception.SystemException;
import com.xiaoy.util.StringUtil;
import com.xiaoy.util.page.PageInfo;
import com.xiaoy.web.BasicAction;

@Namespace("/organization")
@Results( {
	@Result(name = "error", location = "/WEB-INF/content/workspace/exception.jsp", type = "dispatcher"),
	
	@Result(name = "list", location = "/bas/jsp/organization/index.jsp", type = "dispatcher"),
	@Result(name = "addorg", location = "/bas/jsp/organization/addorg.jsp", type = "dispatcher"),
	@Result(name = "saveorg", location = "/common/jsp/success.jsp", type = "dispatcher"),
	
	@Result(name = "addorgtype", location = "/bas/jsp/organization/addorgtype.jsp", type = "dispatcher"),
	@Result(name = "getalltype", location = "/bas/jsp/organization/getalltype.jsp", type = "dispatcher"),
	@Result(name = "savetype", location = "/common/jsp/success.jsp", type = "dispatcher"),
	@Result(name = "deletetype", location = "/common/jsp/success.jsp", type = "dispatcher"),
	
	@Result(name = "settingRole", location = "/bas/jsp/organization/settingrole.jsp", type = "dispatcher"),
//	@Result(name = "saveRole", location = "settingRole", type = "dispatcher"),
	
	
})
public class OrganizationAction extends BasicAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4564902274546448770L;

	private Organization organization ;
	
	@Resource(name="partyTypeSerivce")
	private PartyTypeSerivce partyTypeSerivce;
	@Resource(name="organizationService")
	private OrganizationService organizationService;
	
//	@Resource(name="organizationService")
//	private PartyRoleSerivce partyRoleSerivce;
	
//	@Resource(name="roleService")
//	private RoleService roleService;
	
	
	
	private String resultName;
	
	public String list () {
		
		return "list";
	}
	
	public void getOrgRoot (){
		try {
			List<Organization> orgs = organizationService.getOrgRoot();
			StringBuilder json = new StringBuilder("[ ");
			for (Organization org :orgs) {
				json.append(OrgToTreeNode(org)).append(",");
			}
			json.setCharAt(json.length() - 1, ' ');
			json.append("]");
			
			System.out.println("json-->"+json.toString());
			Struts2Utils.renderJson(json.toString());
		}catch (Exception e) {
			logger.error("初始组织结构错误",e);
			throw new SystemException("初始组织结构错误！");
		}
		
	}
	
	
	
	public String addOrg() {
		
		//获得类型
		getAllType();
		
		
		return "addorg";
	}
	
	public String saveOrg () {
		
		String name = getParameter("name");
		long priority = getParameterLong("priority");
		long sort = getParameterLong("sort");
		long typeid = getParameterLong("typeid");
		long parentid = getParameterLong("parentid");
		
		System.err.println("parentid-->"+parentid+"  typeid-->"+typeid);
		Organization org = new Organization();
		org.setName(name);
		org.setPriority(priority);
		org.setSort(sort);
		organizationService.saveOrUpdate(org, typeid, parentid);
		
		PageInfo page = new PageInfo();
		page.setAutoUrl("organization/organization!addOrg.do");
		page.setAutoInfo("秒钟后，将返回组织机构添加页面！");
		page.setBackUrl("organization/organization!addOrg.do");
		page.setBackInfo("继续添加");
		page.setMessage("保存组织结构(<b>"+name+"</b>)完成.");
		request.setAttribute("pageInfo", page);
		
		return "saveorg";
	}
	
	public void changeType () {
		
		String typeid = getParameter("typeid");
		List<Organization> orgs = organizationService.getParentOrgByTypeid(typeid);
		StringBuilder sb = new StringBuilder("[ ");
		for (Organization org : orgs) {
			
			sb.append("{")
				.append(getJson("name",org.getName())).append(",")
				.append(getJson("id",org.getId())).append(",")
				.append(getJson("text",org.getName())).append(",");
			
				if(org.getParent()!=null){
					sb.append(getJson("pId",org.getParent().getId()));
				}else {
					sb.append(getJson("pId",0));
				}
			;
			sb.append("},");
		}
		sb.setCharAt(sb.length() - 1, ' ');
		sb.append("]");
		System.out.println(sb.toString());
		Struts2Utils.renderJson(sb.toString());
//		JSONArray a =JSONArray.fromObject(orgs);  
//		System.out.println(a.toString()); 
//		String json = JSONUtils.listToJson(orgs);
//		System.out.println(json); 
		
//		logger.info(sb.toString());
	}
	
	private String OrgToTreeNode (Organization org) {
		
		StringBuilder json = new StringBuilder("{ ");
		
		json
		.append(getJson("id",org.getId())).append(",")
		.append(getJson("code",org.getName())).append(",")
		.append(getJson("text",org.getName()));
		
		if (org.getPartyType() != null) {
			json.append(",").append(getJson("typeid",org.getPartyType().getId()))
			.append(",").append(getJson("type",org.getPartyType().getName()));
		}
		
		if (org.getChildren()!=null&&org.getChildren().size()>0) {
			json.append(",").append("\"children\":[ ");
			for (Party p :org.getChildren()) {
				Organization o = (Organization)p;
				json.append(OrgToTreeNode(o)).append(",");
			}
			json.setCharAt(json.length() - 1, ' ');
			json.append("]");
		}
		json.append("}");
		return json.toString();
	}
	
	public void testTree (){
		
		String typeid = getParameter("typeid");
		List<Organization> roots = organizationService.getParentOrgWithTreeByTypeid(typeid);
		
		StringBuilder json = new StringBuilder("[ ");
		for (Organization org :roots) {
			json.append(OrgToTreeNode(org)).append(",");
		}
		json.setCharAt(json.length() - 1, ' ');
		json.append("]");
		
		System.out.println("json-->"+json.toString());
		Struts2Utils.renderJson(json.toString());
	}
	
//	public String rootTree (List<Organization> parents) {
//		StringBuilder json = new StringBuilder("[ ");
//		for (Organization org :parents) {
//			json.append("{")
//			.append(getJson("id",org.getId())).append(",")
//			.append(getJson("text",org.getName())).append(",")
//			.append("\"children\":");
//			if (org.getChildren().size()>0) {
//				
//				
//			}
//			
//			;
//		}
//		json.append("]");
//		return json.toString();
//	}
	
	
	
	public String getJson(String key ,Object value){
		return StringUtil.toJsonAttr(key, value);
	}
	
	public String saveRole () {
		
		String roleIds = getParameter("roleids");
		String[] r_ids = roleIds.split(",");
		long[]ids = StringUtil.toLong(r_ids);
		long orgId = getParameterLong("orgid");
		
		List<PartyRole>partyRoles = new ArrayList<PartyRole>();
		
		for (long r_id:ids) {
//			Role role = new Role(r_id);
			
			partyRoles.add(new PartyRole(r_id));
//			organizationService.
//			partyRoleSerivce.
		}
//		partyRoleSerivce.saveOrUpdates(partyRoles) ;
		organization = organizationService.getById(orgId);
		organization.setPartyRoles(partyRoles);
		
		organizationService.saveOrUpdate(organization);
		
		return "saveRole";
	}
	
	
	public String settingRole () {
		
		long orgid = getParameterLong("orgid");
		
		// 组织结构
		organization = organizationService.getById(orgid);
		
		
//		// 候选角色
		String r = "[$result]";
		String result = "";
//		if (organization.getPartyRoles().size()>0) {
//			organization.getPartyRoles().get(0);
//			result 
			for (int i = 0;i<organization.getPartyRoles().size();i++) {
				PartyRole partyRole = organization.getPartyRoles().get(i);
				if (partyRole.getRole()!=null) {
					result += partyRole.getRole().getId()+",";
				}
			}
//		}
		r=r.replace("$result", result);
		request.setAttribute("checkedRoleId", r);
		
		return "settingRole";
	}
	
//	public void sss () {
//		
//		String typeid = request.getParameter("typeid");
//		List<Organization> orgs = organizationService.getByTypeid(typeid);
//		
//		StringBuilder sb = new StringBuilder("[");
//		
//		for (Organization org : orgs) {
//			sb.append("{").append("name:").append(org.getName()).append(",id:").append(org.getId()).append("}");
//		}
//		sb.append("]");
//		logger.info(sb.toString());
////		Struts2Utils.renderJson(sb.toString());
//		logger.info("sss i am coming");
//		
//	}
	
	
	
	
	// 类型部分 -----------------start
	
	public String addOrgType () {
		
		return "addorgtype";
	}
	public String getAllType () {
		
		List<PartyType>types = partyTypeSerivce.getAll();
		request.setAttribute("types", types);
		logger.info("getAllType");
		return "getalltype";
	}
	
	public String addType(){
		
		
		return "addtype";
	}
	
	public String saveType() throws SystemException {
		String name = getParameter("name");
		long priority = getParameterLong("priority");
		PartyType type = new PartyType(name,priority);
		
		try {
			partyTypeSerivce.save(type);
			logger.info("保存组织结构类型完成:"+name);
			
			PageInfo page = new PageInfo();
			page.setAutoUrl("bas/jsp/organization/addtype.jsp");
			page.setAutoInfo("秒钟后，将返回组织机构类型添加页面！");
			page.setBackUrl("bas/jsp/organization/addtype.jsp");
			page.setBackInfo("继续添加");
			page.setMessage("保存组织结构类型(<b>"+name+"</b>)完成.");
			request.setAttribute("pageInfo", page);
			
		} catch (Exception e) {
			
			logger.error("保存组织结构类型错误"+e.getMessage());
			throw new SystemException("保存组织结构类型错误"+e.getMessage());
		}
		
		return "savetype";
	}
	
	public String deleteType () throws SystemException {
		
		long id = getParameterLong("id");
		try {	
			
			PartyType type = partyTypeSerivce.delete(id);
			logger.info("删除组织结构类型完成:id-->"+id +"  名称："+type.getName());
			
			PageInfo page = new PageInfo();
			page.setAutoUrl("organization/organization!getAllType.do");
			page.setAutoInfo("秒钟后，将返回组织机构类型列表页面！");
			page.setBackUrl("organization/organization!getAllType.do");
			page.setBackInfo("返回列表页面");
			page.setMessage("删除组织结构类型(<b>"+type.getName()+"</b>)完成.");
			request.setAttribute("pageInfo", page);
			
			
			
		} catch (Exception e) {
			
			logger.error("保存组织结构类型错误"+e.getMessage());
			e.printStackTrace();
			throw new SystemException("删除组织结构类型错误"+e.getMessage());
		}
		return "deletetype";
	}
	
	public String delete () {
		
		long orgid= getParameterLong("orgid");
		System.err.println("orgid-->"+orgid);
		return "delete";
	}
	
	//----------------------------
	public String getResultName() {
		return resultName;
	}

	public void setResultName(String resultName) {
		this.resultName = resultName;
	}

	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}
	
}
